<template>
	<!-- 主要内容区域 -->
	<view class="container">
		<view class="upload-title">城市牛皮癣清理上报</view>
		<view style="color: #4b5563;margin-bottom: 1.5rem;text-align: center;">
			帮助我们共同维护城市环境整洁
		</view>

		<view class="upload-area">
			<view class="upload-item">
				<view class="upload-box" v-if="!pageData.picture1" @tap="chooseBeforeImage">
					<uni-icons type="upload" size="28" color="#999999"></uni-icons>
					<text class="upload-text">拍摄处理前照片</text>
				</view>
				<view class="upload-box" v-else @tap="lookDetail(pageData.picture1)">
					<image style="width: 100%;height: 100%;" :src="pageData.picture1"></image>
				</view>
			</view>
			<view class="upload-item">
				<view class="upload-box" v-if="!pageData.picture2" @tap="chooseAfterImage">
					<uni-icons type="upload" size="28" color="#999999"></uni-icons>
					<text class="upload-text">拍摄处理后照片</text>
				</view>
				<view class="upload-box" v-else @tap="lookDetail(pageData.picture2)">
					<image style="width: 100%;height: 100%;" :src="pageData.picture2"></image>
				</view>
			</view>

		</view>

		<view class="location-section">
			<view style="margin-bottom: 10rpx;color: #666; text-align: right;" @click="handleNavigateToMap">
				治理范围
				<uni-icons class="map-icon" type="location" size="16" color="#07c160"></uni-icons>
			</view>
			<view class="location-wrapper">
				<view class="location-left">
					<uni-icons type="location" size="20" color="#333333"></uni-icons>
					<text class="location-text">{{locationInfo.name}}</text>
				</view>
				<view class="refresh-btn" :class="{ 'refreshing': isRefreshing }" @click="getAddress">
					<uni-icons type="refresh" size="20" color="#2563eb"></uni-icons>
				</view>
			</view>
		</view>

		<view class="remark-section">
			<textarea class="remark-input" v-model="remarkText" placeholder="请输入备注信息（选填）"
				placeholder-style="color: #999999;" />
		</view>
		<button class="submit-btn" type="primary" style="display: inline-table;" @click="handleSubmit">提交</button>

		<view
			style="text-align: center;color: #6b7280;font-size: 14px;width: calc(100% - 60rpx);margin-top: 3rem;margin-bottom: 1rem;">
			<view style="">
				感谢您为城市环境整洁做出的贡献
			</view>
			<view style="margin-top: 0.25rem ">
				© 2025 环投环境
			</view>
		</view>
		<canvas canvas-id="photoCanvas" :style="{'width': pageData.w , 'height': pageData.h }"
			style="position: fixed; left: -9999px; top: -9999px;"></canvas>
	</view>

</template>

<script setup lang="ts">
	import {
		onMounted,
		ref,
		reactive
	} from 'vue';
	import {
		authorization,
		getLocation,
		isPointInPolygonOptimized
	} from '@/utils/location.js'
	import {
		request
	} from '@/utils/api';
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		imagePath
	} from '@/config/common.js'
	import dayjs from '@/utils/dayjs.main.js'
	const remarkText = ref("")
	//Canvas
	let ctx : any = {};
	let pageData = reactive({
		isAddressOk: false,
		picture1: '', //第一张照片的本地路径
		picture2: '', //第二张照片的本地显示路径
		firstUploadInfo: {} as any, //上传的第一张照片信息
		lastUploadInfo: {} as any, //上传的第二张照片信息
		postUrl: null, //上传照片的路径
		w: '0px', //拍照的照片的宽度
		h: '0px', //拍照的照片高度
		postPhotoInfo: {} as any, //上传照片的信息
	})
	let postImageTime = reactive({
		startTime: '',
		endTime: ''
	})
	const handleNavigateToMap = () => {
		uni.navigateTo({
			url: '/pages/range/range'
		})
	}

	const chooseBeforeImage = async () => {
		locationInfo.value = ''
		await getAddress();
		if (!pageData.isAddressOk) {
			return
		}
		commonUploadPhoto('picture1');
	}
	const chooseAfterImage = () => {
		if (!pageData.picture1) {
			uni.showToast({
				title: '请先拍摄处理前的照片',
				icon: 'none'
			})
			return
		}
		commonUploadPhoto('picture2');
	}
	/**
	 * 获取上传路径
	 */
	const getpostPhotoUrl = () => {
		return new Promise((resolve, reject) => {
			request({
				url: '/sanitation/v1/oss-upload-url',
				method: 'post',
				data: {
					bucketName: "images",
					contentType: 'image/jpeg',
					method: 1,
					filePath: 'tourist/' + dayjs().format('YYYYMMDD')
				}
			}).then(res => {
				pageData.postUrl = res.uploadUrl.replace(
					/http:\/\/localhost:9000/g,
					imagePath).replace(
						/http:\/\/47\.108\.149\.34:9000/g,
						imagePath);
				res.uploadUrl = pageData.postUrl
				pageData.postPhotoInfo = res;
				resolve(res)
			}).catch(e => {
				reject(e)
			})
		})
	}
	/**
	 * 处理处理之前照片
	 */
	const commonUploadPhoto = async (pictureType : 'picture1' | 'picture2') => {
		pageData.postUrl = null;
		/* if (!pageData.postUrl) */
		await getpostPhotoUrl()
		console.log("test")
		uni.chooseMedia({
			count: 1, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['camera'], //['camera'], //拍照
			mediaType: ['image'],
			success: function (res : UniApp.ChooseMediaSuccessCallbackResult) {
				uni.showLoading({
					mask: true
				})
				uni.getImageInfo({
					src: res.tempFiles[0].tempFilePath,
					success: (ress) => {
						console.log(ress)
						pageData.w = ress.width + 'px';
						pageData.h = ress.height + 'px';

						let st = setTimeout(() => {
							/** 创建画布 */
							//将图片src放到cancas内，宽高为图片大小
							ctx.drawImage(res.tempFiles[0].tempFilePath, 0, 0,
								ress.width, ress
								.height)

							ctx.setFontSize(50)
							ctx.setFillStyle('#8a2929')

							ctx.setTextAlign('right')
							ctx.fillText(dayjs().format('YYYY.MM.DD HH:mm') +
								'  ' + (
									locationInfo.value.street || ''), ress
										.width -
							30, ress
								.height - 40)



							let quality = (res.tempFiles[0].size /
								1000000 > 5) ? 0.2 :
								0.3

							ctx.draw(true, () => {
								let st1 = setTimeout(() => {
									uni.canvasToTempFilePath({
										canvasId: 'photoCanvas',
										fileType: 'jpg',
										quality, //: 0.5,
										success: (
											res1
										) => {
											pageData[
												pictureType
											] =
												res1
													.tempFilePath;

											uni.hideLoading()
											uploadPhoto
												(
													pictureType)
										}
									});
									clearTimeout(st1)
								}, 300);
							});
							clearTimeout(st)
						}, 100)

					}
				})
			}
		});
	}

	/**
	 * 上传照片
	 *@param pictureType {string}  picture1|picture2
	 */
	const uploadPhoto = (pictureType : 'picture1' | 'picture2') => {
		// #ifdef MP-WEIXIN
		if (uni.getSystemInfoSync().platform === 'ios') {
			uni.compressImage({
				src: pageData[pictureType],
				quality: 30,
				success: res => {
					// pageData.postUrl = res.tempFilePath
					pageData[pictureType] = res.tempFilePath;
					uni.showLoading({
						title: "上传图片中。。。",
						mask: true
					})
					let setI = setInterval(() => { //确保有上传路径才上传照片
						if (pageData.postUrl) {
							clearInterval(setI)
							commonUpload(pictureType)
						}
					}, 100)
				}
			})
		} else {
			uni.showLoading({
				title: "上传图片中。。。",
				mask: true
			})
			let setI = setInterval(() => { //确保有上传路径才上传照片
				if (pageData.postUrl) {
					clearInterval(setI)
					commonUpload(pictureType)
				}
			}, 100)
		}
		// #endif
		// #ifndef MP-WEIXIN
		uni.showLoading({
			title: "上传图片中。。。",
			mask: true
		})
		let setI = setInterval(() => { //确保有上传路径才上传照片
			if (pageData.postUrl) {
				clearInterval(setI)
				commonUpload(pictureType)
			}
		}, 100)
		// #endif




	}

	/**
	 * @param pictureType {string}  picture1|picture2
	 */
	const commonUpload = (pictureType : 'picture1' | 'picture2') => {

		console.log("pageData.postPhotoInfo", pageData.postPhotoInfo)
		uni.uploadFile({
			url: pageData.postPhotoInfo.uploadUrl, //param[0],
			filePath: pageData[pictureType],
			name: 'file',
			header: {
				'content-type': 'multipart/form-data'
			},
			formData: pageData.postPhotoInfo.formData,
			success: () => {
				uni.hideLoading()
				pageData.postUrl = null
				if (pictureType == 'picture1') {
					pageData.postUrl = null
					pageData.firstUploadInfo = JSON.parse(JSON.stringify(pageData
						.postPhotoInfo));
					postImageTime.startTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

				} else {
					pageData.postUrl = null
					pageData.lastUploadInfo = JSON.parse(JSON.stringify(pageData
						.postPhotoInfo));
					postImageTime.endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

				}
				pageData.postPhotoInfo = {}

			},
			fail(err) {
				console.log(err)
				uni.hideLoading()
			}
		});

	}


	/**
	 * 查看照片
	 */
	const lookDetail = (tempFilePath : string) => {
		uni.previewImage({
			urls: [tempFilePath],
			current: 0,
		});
	}


	const handleSubmit = () => {
		if (!pageData.picture1) {
			uni.showToast({
				icon: 'none',
				title: '缺失处理之前的照片'
			})
			return
		}
		if (!pageData.picture2) {
			uni.showToast({
				icon: "none",
				title: "缺失处理之后的照片"
			})
			return
		}
		if (!locationInfo.value.name) {
			uni.showToast({
				icon: "none",
				title: "缺少位置信息，请打开GPS，或者刷新位置信息"
			})
			return
		}
		let postData : PosterItem = {
			beforePhoto: pageData.firstUploadInfo.fileName,
			afterPhoto: pageData.lastUploadInfo.fileName || '',
			posterType: '乱张贴',
			position: {
				latitude: ('' + locationInfo.value.latitude) || '',
				longitude: ('' + locationInfo.value.longitude) || ''
			},
			status: 'UNTREATED',//UNTREATED PENDING TREATED
			street: locationInfo.value.street || '',
			phoneNumbers: [],
			// #ifdef MP-WEIXIN
			positionDescription: locationInfo.value.name,
			//#endif
			remark: remarkText.value || '',
			type: '',
			contribute: true
		}
		postData.operateTime = dayjs(postImageTime.endTime).diff(postImageTime.startTime, 'minute')
		console.log(postData)
		request({
			url: '/sanitation/v1/posters',
			method: 'POST',
			data: postData
		}).then(res => {
			remarkText.value = '';
			pageData.firstUploadInfo = {};
			pageData.lastUploadInfo = {};
			pageData.picture1 = '';
			pageData.picture2='';
			postImageTime.startTime = '';
			postImageTime.endTime = '';



			uni.showToast({
				title: "清理上传成功",
				icon: 'none'
			})
		})
	}


	//latitude longitude desc name street formatted_address
	let locationInfo = ref<any>({})
	const isRefreshing = ref(false)
	const getAddress = async () => {
		locationInfo.value = {}
		isRefreshing.value = true
		uni.showLoading()
		try {
			locationInfo.value = await getLocation();
			pageData.isAddressOk = isPointInPolygonOptimized({ latitude: locationInfo.value.latitude, longitude: locationInfo.value.longitude });//true
			console.log(pageData.isAddressOk)
			if (!pageData.isAddressOk) {
				uni.showToast({
					title: "当前所在位置不在范围之内,请刷新定位或者进入指定治理范围内",
					icon: "none"
				})
			}

		} catch (e) {

		}
		isRefreshing.value = false
		uni.hideLoading()
	}
	onLoad(async () => {
		ctx = uni.createCanvasContext('photoCanvas');
		authorization();
		await getAddress();
	})
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
	}

	.container {
		min-height: 100%;
		padding: 0 30rpx;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
		position: relative;
		height: 100vh;
		overflow-y: auto;
	}

	.upload-title {
		font-size: 20px;
		color: #2563eb;
		margin-bottom: 0.5rem;
		font-weight: bold;
		text-align: center;
	}

	.upload-area {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
	}

	.upload-item {
		width: 330rpx;
		height: 330rpx;
	}

	.upload-box {
		width: 100%;
		height: 100%;
		background-color: #ffffff;
		border-radius: 8px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border: #d1d5db 1px dashed;
	}

	.upload-text {
		font-size: 14px;
		color: #999999;
		margin-top: 16rpx;
	}

	.location-section {
		margin-bottom: 30rpx;
	}

	.location-wrapper {
		background-color: #eff6ff;
		padding: 24rpx;
		border-radius: 8px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.location-left {
		display: flex;
		align-items: center;
		flex: 1;
		margin-right: 20rpx;
	}

	.location-text {
		font-size: 14px;
		color: #333333;
		margin-left: 12rpx;
		flex: 1;
	}

	.refresh-btn {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.refreshing {
		animation: rotate 1s linear infinite;
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.remark-section {
		background-color: #ffffff;
		border-radius: 8px;
		padding: 24rpx;
		margin-bottom: 60rpx;
	}

	.remark-input {
		width: 100%;
		height: 200rpx;
		font-size: 14px;
		color: #333333;
		line-height: 1.5;
	}

	.submit-btn {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background-color: #007AFF;
		color: #ffffff;
		font-size: 16px;
		border-radius: 8px;
	}
</style>